<template>
  <el-container class="exchange">
    <el-main>
      <el-card shadow="never" class="tableCard">
        <vxe-toolbar :refresh="{query: getList1}" >
          <template v-slot:buttons>
           <el-button type="info" icon="el-icon-tickets" @click="openTemplateDialog({})">邮件模板</el-button>
          </template>
        </vxe-toolbar>
        <vxe-table
          ref="xTree"
          border
          row-key
          resizable
          highlight-hover-row
          :auto-resize="true"
          :data="list"
          width
          max-height="500"
          row-id="id"
          highlight-current-row
          text-algin="center"
          :print-config="{}"
          header-align="center" >
          <vxe-table-column
            field="name"
            width="200"
            align="center"
            title="服务器名称"
          />
          <vxe-table-column
            field="sendHost"
            width="180"
            align="center"
            title="服务器地址"
          />
          <vxe-table-column
            field="senderEmail"
            width="180"
            align="center"
            title="邮件账号"
          />
          <vxe-table-column
            show-overflow
            title="备注"
            field="remark"
            align="left"
            min-width="250"
          />
          <vxe-table-column
            show-overflow
            title="默认"
            field="haveDefault"
            align="left"
            width="100"
          >
           <template slot-scope="scope">
             <el-switch v-model="scope.row.haveDefault" :inactive-value="0" :active-value="1" active-text inactive-text @change="changeEmailConfigDefaultState(scope)" />
           </template>
          </vxe-table-column>
          <vxe-table-column
            show-overflow
            title="状态"
            field="publishStatus"
            align="left"
            width="100"
          >
           <template slot-scope="scope">
             <el-switch v-model="scope.row.publishStatus" :inactive-value="0" :active-value="1" active-text inactive-text @change="changeEmailConfigPublishState(scope)" />
           </template>
          </vxe-table-column>
          <vxe-table-column
            title="操作"
            fixed="right"
            align="center"
            width="120"
          >
            <template slot-scope="scope">
              <div class="drag-btn">
                <el-button
                  type="text"
                  size="mini"
                  @click="openConfigDialog(scope.row)"
                >配置</el-button>
              </div>
            </template>
          </vxe-table-column>
        </vxe-table>
      </el-card>

      <el-dialog width="45%" :close-on-click-modal="false" :modal="false" :visible.sync="dialogTemplateVisible" title="模板配置">
         <vxe-table
           ref="xTree"
           border
           row-key
           resizable
           highlight-hover-row
           :auto-resize="true"
           :data="templateList"
           width
           max-height="500"
           row-id="id"
           highlight-current-row
           text-algin="center"
           :print-config="{}"
           header-align="center" >
           <vxe-table-column field="templateCode" width="150" align="center" title="模板编码" />
           <vxe-table-column field="templateName" min-width="220" align="left" title="模板名称" />
           <vxe-table-column show-overflow title="状态" field="publishStatus" align="left" width="80" >
             <template slot-scope="scope">
               <el-switch v-model="scope.row.publishStatus" :inactive-value="0" :active-value="1" active-text inactive-text @change="changeEmailTemplatePublishStatus(scope)" />
             </template>
           </vxe-table-column>
           <vxe-table-column title="操作" fixed="right" align="center" width="120" >
             <template slot-scope="scope">
               <div class="drag-btn">
                 <el-button type="text" size="mini"  @click="openTemplateEditDialog(scope.row)" >设置</el-button>
               </div>
             </template>
           </vxe-table-column>
         </vxe-table>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogTemplateVisible = false">关 闭</el-button>
        </div>
      </el-dialog>
      <el-dialog width="50%" :close-on-click-modal="false" :modal="false" :visible.sync="dialogTemplateEditVisible" title="模板编辑">
         <el-form ref="ruleTemplateForm" :model="templateParams" label-width="7rem" :rules="templateRules">
           <el-row :gutter="40">
             <el-col :span="22">
               <el-form-item label="模板编码：" prop="templateCode">
                 <el-input v-model="templateParams.templateCode" :disabled="true"/>
               </el-form-item>
             </el-col>
             <el-col :span="22">
               <el-form-item label="模板名称：" prop="templateName">
                 <el-input v-model="templateParams.templateName"  :disabled="true"/>
               </el-form-item>
             </el-col>
             <el-col :span="22">
               <el-form-item label="邮件标题名称：" prop="templateSubject">
                 <el-input v-model="templateParams.templateSubject"  :disabled="templateEditDisabled"/>
               </el-form-item>
             </el-col>
             <el-col :span="22">
               <el-form-item label="模板内容：" prop="templateContent">
                 <el-input id="templateContent" v-model="templateParams.templateContent" type="textarea" :rows="5"  :disabled="templateEditDisabled" />
                 <div style="height: 100px;line-height: 20px;">
                    <el-menu  @select="insertTemplateParam" :collapse="true" active-text-color="#000" v-if="!templateEditDisabled">
                      <el-submenu>
                        <template slot="title"> <i class="el-icon-document"></i> </template>
                        <el-menu-item
                            v-for="item in templateParamList"
                            :key="item.templateParam"
                            :index="item.templateParam"
                        >{{item.templateParamDesc}}</el-menu-item>
                      </el-submenu>
                    </el-menu>
                 </div>
               </el-form-item>
             </el-col>
           </el-row>
         </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogTemplateEditVisible = false">关 闭</el-button>
          <el-button v-if="!templateEditDisabled" type="primary" @click="templateSubmit">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog width="50%" :close-on-click-modal="false" :modal="false" :visible.sync="dialogConfigVisible" title="邮件配置">
         <el-form ref="ruleConfigForm" :model="configParams" label-width="7rem" :rules="configRules">
           <el-row :gutter="40">
             <el-col :span="12">
               <el-form-item label="服务器名称:" prop="name">
                 <el-input v-model="configParams.name" :disabled="configEditDisabled"/>
               </el-form-item>
             </el-col>
             <el-col :span="12">
               <el-form-item label="服务器协议:" prop="templateName" placeholder="请选择">
                 <el-select v-model="configParams.sendProtocol"  :disabled="configEditDisabled">
                   <el-option label="SMTP" value="smtp" />
                   <el-option label="IMAP" value="imap" />
                 </el-select>
               </el-form-item>
             </el-col>
             <el-col :span="12">
               <el-form-item label="服务器地址:" prop="sendHost">
                 <el-input v-model="configParams.sendHost"  :disabled="configEditDisabled"/>
               </el-form-item>
             </el-col>
             <el-col :span="12">
               <el-form-item label="服务器端口:" prop="sendPort">
                 <el-input v-model="configParams.sendPort"  :disabled="configEditDisabled"/>
               </el-form-item>
             </el-col>
             <el-col :span="12">
               <el-form-item label="邮箱账号:" prop="senderEmail">
                 <el-input v-model="configParams.senderEmail"  :disabled="configEditDisabled"/>
               </el-form-item>
             </el-col>
             <el-col :span="12">
               <el-form-item label="邮箱密码:" prop="senderEmailPassword">
                 <el-input v-model="configParams.senderEmailPassword"  :disabled="configEditDisabled" show-password/>
               </el-form-item>
             </el-col>
             <el-col :span="24">
               <el-form-item label="SSL认证:" prop="needSsl">
                 <el-checkbox v-model="configParams.needSsl" :true-label="1" :false-label="0"  :disabled="configEditDisabled"></el-checkbox>
               </el-form-item>
             </el-col>
             <el-col :span="12" v-show="configParams.needSsl">
               <el-form-item label="授权码:">
                 <el-input v-model="configParams.emailConfigSsl.senderAuthCode"  :disabled="configEditDisabled"/>
               </el-form-item>
             </el-col>
             <el-col :span="12"  v-show="configParams.needSsl">
               <el-form-item label="TLS要求:" prop="requireTls">
                 <el-checkbox v-model="configParams.emailConfigSsl.requireTls" :true-label="1" :false-label="0"  :disabled="configEditDisabled"></el-checkbox>
               </el-form-item>
             </el-col>
             <el-col :span="12"  v-show="configParams.needSsl">
               <el-form-item label="用户名:" prop="userName">
                 <el-input v-model="configParams.emailConfigSsl.userName"  :disabled="configEditDisabled"/>
               </el-form-item>
             </el-col>
             <el-col :span="12"  v-show="configParams.needSsl">
               <el-form-item label="用户密码:" prop="userPassword">
                 <el-input v-model="configParams.emailConfigSsl.userPassword"  :disabled="configEditDisabled"/>
               </el-form-item>
             </el-col>
             <el-col :span="24">
               <el-form-item label="备注:" prop="remark">
                 <el-input v-model="configParams.remark" type="textarea" :rows="2"  :disabled="configEditDisabled" />
               </el-form-item>
             </el-col>
           </el-row>
         </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogConfigVisible = false">关 闭</el-button>
          <el-button v-if="!configEditDisabled" type="primary" @click="configSubmit">确 定</el-button>
        </div>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
import { listEmailConfig,viewEmailConfig,modifyEmailConfig, changeEmailConfigPublishStatus, changeEmailConfigDefaultStatus,
 listEmailTemplateParam, listEmailTemplate,viewEmailTemplate, modifyEmailTemplate, changeEmailTemplateStatus} from '@/api/messageSetting'
export default {
  data() {
    return {
      title: '',
      configEditDisabled: false,
      templateEditDisabled: false,
      dialogConfigVisible: false,
      dialogTemplateVisible: false,
      dialogTemplateEditVisible: false,
      configParams: {
        name:'',
        sendProtocol:'',
        sendHost:'',
        sendPort:'',
        senderEmail:'',
        senderEmailPassword:'',
        remark:'',
        haveDefault:'',
        needSsl: 1,
        emailConfigSsl: {
          senderAuthCode:'',
          requireTls: 0,
          userName:'',
          userPassword:'',
          encoding:'UTF-8'
        }
      },
      templateParams: {
        templateCode:'',
        templateName:'',
        templateContent:''
      },
      configRules:{
        name: [{ required: true, message: '请输入服务器名称', trigger: 'change' }],
        sendHost: [{ required: true, message: '请输入服务器地址', trigger: 'blur' }],
        sendPort: [{ required: true, message: '请输入服务器端口', trigger: 'change' }],
        senderEmail: [{ required: true, message: '请输入邮箱账号', trigger: 'blur' }]
      },
      templateRules:{},
      list: [],
      templateList: [],
      templateParamList: [],
      flag:true
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList1(){
      this.getList()
    },
    // 列表
    getList() {
      listEmailConfig({}).then(res =>{
        if(res){
          if(res.code){
            this.$message.error(`${res.msg}`);
          }else{
            this.list = res
          }
        }
      })
    },
    // 模板窗
    openTemplateDialog(id) {
      this.dialogTemplateVisible = true
      this.getTemplateList()
   },
   getTemplateList() {
     listEmailTemplate({}).then(res =>{
       if(res){
         if(res.code){
           this.$message.error(`${res.msg}`);
         }else{
           this.templateList = res
         }
       }
     })
   },
   getTemplateParamList() {
     if(this.templateParams.id){
       listEmailTemplateParam(this.templateParams.id).then(res =>{
         if(res){
           if(res.code){
             this.$message.error(`${res.msg}`);
           }else{
             this.templateParamList = res
           }
         }
       })
     }else{
       this.templateParamList =[]
     }
   },
   insertTemplateParam(key) {
      let elInput = document.getElementById('templateContent')
      let startPos = elInput.selectionStart

      let endPos = elInput.selectionEnd

      if (startPos === undefined || endPos === undefined) {
          elInput.value= key
      } else {
          let txt = elInput.value
          let result = txt.substring(0, startPos) + key + txt.substring(endPos)
          elInput.value= result
      }
      elInput.$nextTick(() => {
          elInput.focus()
          elInput.selectionStart = startPos + key.length
          elInput.selectionEnd = startPos + key.length
      })

   },
   openTemplateEditDialog(row){
     this.dialogTemplateEditVisible = true
     this.templateEditDisabled = row.publishStatus === 1? true:false
     if(row.id){
       viewEmailTemplate(row.id).then(res =>{
         if(res){
           if(res.code){
             this.$message.error(`${res.msg}`);
           }else{
             this.templateParams = res
             this.getTemplateParamList()
           }
         }
       })
     }else{
       alert('打开编辑器錯誤')
       return false
     }
   },
    // 新增 编辑
    openConfigDialog(row) {
      this.dialogConfigVisible = true

      this.configEditDisabled = row.publishStatus ===1?true:false
      if(row.id){
        this.flag = true
        viewEmailConfig(row.id).then(res =>{
          if(res){
            if(res.code){
              this.$message.error(`${res.msg}`);
            }else{
              this.configParams = res
              if(res.emailConfigSsl == null){
                 this.configParams.emailConfigSsl = {senderAuthCode:'', requireTls: 0, userName:'', userPassword:'', encoding:'UTF-8'}
              }
            }
          }
        })
      }else{
        this.flag = false
        Object.keys(this.configParams).forEach(key => this.configParams[key] = '')
      }
    },
    changeEmailConfigDefaultState(scope){
        this.list[scope.seq - 1].haveDefault =  scope.row.haveDefault === 1 ? 0 : 1
        changeEmailConfigDefaultStatus({
          id: scope.row.id,
          status: scope.row.haveDefault === 1 ? 0 : 1
        }).then((response) => {
          this.list[scope.seq - 1].haveDefault =  scope.row.haveDefault === 1 ? 0 : 1
          this.$message.success( scope.row.haveDefault === 0 ? '取消成功' : '启用成功' )
          this.getList()
        })
    },
    changeEmailConfigPublishState(scope){
        this.list[scope.seq - 1].publishStatus =  scope.row.publishStatus === 1 ? 0 : 1
        changeEmailConfigPublishStatus({
          id: scope.row.id,
          status: scope.row.publishStatus === 1 ? 0 : 1
        }).then((response) => {
          this.list[scope.seq - 1].publishStatus = scope.row.publishStatus === 1 ? 0 : 1
          this.$message.success( scope.row.publishStatus === 0 ? '禁用成功' : '启用成功' )
        })
    },
    changeEmailTemplatePublishStatus(scope){
        this.templateList[scope.seq - 1].publishStatus = scope.row.publishStatus === 1 ? 0 : 1
        changeEmailTemplateStatus({
          id: scope.row.id,
          status: scope.row.publishStatus === 1 ? 0 : 1
        }).then((response) => {
          this.templateList[scope.seq - 1].publishStatus = scope.row.publishStatus === 1 ? 0 : 1
          this.$message.success( scope.row.publishStatus === 0 ? '禁用成功' : '启用成功' )
        })
    },
    templateSubmit(){
      modifyEmailTemplate(this.templateParams).then(res=>{
        if(res){
          if(res.code){
            this.$message.error(`${res.msg}`);
          }else{
            this.$message.success('保存成功!')
            this.getTemplateList()
            this.dialogTemplateEditVisible = false
          }
        }
      })
    },
    // 保存
    configSubmit(){
      if(this.flag){
        modifyEmailConfig(this.configParams).then(res=>{
          if(res){
            if(res.code){
              this.$message.error(`${res.msg}`);
            }else{
              this.$message.success('保存成功!')
              this.getList()
              this.dialogConfigVisible = false
            }
          }
        })
      }
    }
  }
}
</script>

<style>
  .member-content{
    width: 95%;
    >div{
      .cont-pre{
        margin: 1;
        font-family: auto;
      }
      >span{
        cursor: pointer;
      }
    }
  }
  .el-menu .el-menu--vertical{
     border: none;
   }
  .el-menu .el-menu-item{
     background-color: #fff!important;

   }
   .el-menu .el-menu-item:hover{
     background-color: #fff!important;
   }
   .el-menu .el-submenu__title{
     background-color: #fff!important;
   }
   .el-menu .el-submenu__title:hover{
     background-color: #fff!important;
   }
   .el-menu--vertical .el-menu--popup .el-menu-item{
     min-height: 35px;
     line-height: 30px;
   }
   .el-menu--collapse .el-menu .el-submenu, .el-menu--popup {
      min-width: 150px;
   }
</style>
